package com.cait.cait.controller;

import com.cait.cait.dao.MemberDao;
import com.cait.cait.dao.UserDao;
import com.cait.cait.entity.Member;
import com.cait.cait.entity.User;
import com.cait.cait.resultVo.ResultVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Jirath
 * @date 2020/2/12
 * @description: 用户基础操作，不需要登录也能访问
 */
@Controller
public class UserController extends BasicController {

    @Autowired
    UserDao userDao;
    @Autowired
    MemberDao memberDao;
    /**
     * 用户登录操作，返回json对象，返回状态码在配置文件中
     * @param userName
     * @param userPassword
     * @return
     */
    @RequestMapping("/login/confirm")
    @ResponseBody
    public ResultVo login(@RequestParam String userName, @RequestParam String userPassword){
        //1. Acquire submitted principals and credentials:
        AuthenticationToken token = new UsernamePasswordToken(userName, userPassword);
        //2. Get the current Subject:
        Subject currentUser = SecurityUtils.getSubject();
        //3. Login:
        try {
            currentUser.login(token);
        }catch (UnknownAccountException e){
            return ResultVo.builder().code(statusMsgUtil.getUnknownAccount()).message("unknownAccount").data(null).build();
        } catch (IncorrectCredentialsException ice) {
            return ResultVo.builder().code(statusMsgUtil.getIncorrectPassword()).message("IncorrectPassword").data(null).build();
        } catch (LockedAccountException lae) {
            return ResultVo.builder().code(statusMsgUtil.getLockedAccount()).message("lockedAccount").data(null).build();
        }
        return ResultVo.builder()
                .code(statusMsgUtil.getSucceed())
                .message("login")
                .data(null)
                .build();
    }
    @RequestMapping("/sign_up")
    @ResponseBody
    public ResultVo signUp(Member member, User user){
        userDao.newUser(user);
        memberDao.addMember(member);
        //1. Acquire submitted principals and credentials:
        AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), user.getUserPassword());
        //2. Get the current Subject:
        Subject currentUser = SecurityUtils.getSubject();
        //3. Login:
        currentUser.login(token);
        return ResultVo.builder()
                .build();
    }
}
